package com.btr.ivle;

import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.IVLEAuthTask;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.AESEncryptor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements AsyncTaskCompleteListener<String>{
	
	final private String SEED = "w%B1U,(+8Ls7x(Y,";
	
	private Context myApp = this;
	private ProgressDialog loginProgressDialog;
	private IVLEAuthTask authTask;
	private SharedPreferences sp;
	private String decryptedPw = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
    	final EditText userid = (EditText) findViewById(R.id.editText1);
    	final EditText password = (EditText) findViewById(R.id.editText2);
    	final CheckBox savePwCB = (CheckBox) findViewById(R.id.savePw);
    	final Button btn_login = (Button) findViewById(R.id.btn_login);
        
        savePwCB.setChecked(true); //default remember password
        sp = this.getSharedPreferences("passwordSP", 0);
        if(sp.contains("pw")){
        	try {
				decryptedPw = AESEncryptor.decrypt(SEED, sp.getString("pw", null));
			} catch (Exception e) {
				Toast.makeText(this, "Error in stored password", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
        	userid.setText(sp.getString("id", null));
        	password.setText(decryptedPw);
        }

        btn_login.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
	    		if(isNetworkAvailable()){
			    	if(!userid.getText().toString().equals("")&&!password.getText().toString().equals("")){
				    	loginProgressDialog = ProgressDialog.show(LoginActivity.this, "", 
			                        "Logging in. Please wait...", true);
				    	authTask = new IVLEAuthTask(myApp);
				    	authTask.execute(userid.getText().toString(),password.getText().toString(),getString(R.string.IVLE_API_KEY));
			    	}else{
			    		loginFail();
			    	}
	    		}else{
	    			if(userid.getText().toString().equals(sp.getString("id", null))
	    					&& password.getText().toString().equals(decryptedPw)){
	    				IVLEToken.setToken(null,userid.getText().toString().toUpperCase());
	    				loginSuccess(true);
	    			}else{
	    				loginFail();
	    			}
	    		}
	    	}
        });   
    }
    
    @Override
    public void onDestroy(){
    	if(this.authTask!=null)
    		this.authTask.cancel(true);
    	super.onDestroy();
    }

	public void onAsyncTaskComplete(String result) {
		loginProgressDialog.dismiss();
		if (IVLEToken.getRefreshed()){
			loginSuccess(false);
		}else{
			loginFail();
		}
	}

	public boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
	    return (info != null && info.isConnectedOrConnecting());
	}

	private void loginSuccess(boolean offline){
		IVLEToken.setOffline(offline);
		if(offline){
			Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
		}else
			Toast.makeText(myApp, "You are logged in." , Toast.LENGTH_LONG).show();
		EditText userid = (EditText) findViewById(R.id.editText1);
        EditText password = (EditText) findViewById(R.id.editText2);
        CheckBox savePwCB = (CheckBox) findViewById(R.id.savePw);
		if (savePwCB.isChecked()){
			String encryptedPw = "";
			try {
				encryptedPw = AESEncryptor.encrypt(SEED, password.getText().toString());
			} catch (Exception e) {
				Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
			sp.edit().putString("id", userid.getText().toString()).commit();
			sp.edit().putString("pw", encryptedPw).commit();
		}else{
			sp.edit().clear().commit();
		}
		Intent intent = new Intent(myApp, MainActivity.class);
        startActivity(intent);
        finish();
	}
	
	@SuppressWarnings("deprecation")
	private void loginFail(){
        EditText password = (EditText) findViewById(R.id.editText2);
		AlertDialog ad = new AlertDialog.Builder(myApp).create();
		ad.setTitle("Login Failed");
		ad.setMessage("Please check...");
		password.setText("");
		ad.setButton("Retry", new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int which){
				return;
			}
		});
		ad.show();
	}
	
}